//
//  CTPComposeViewController.m
//  LittleNotes
//
//  Created by 檀志文 on 16/5/19.
//  Copyright © 2016年 ios檀志文. All rights reserved.
//

#import "CTPComposeViewController.h"
#import "CTPPlaceholderTextView.h"
#import <Masonry.h>
#import "UIBarButtonItem+Extension.h"
#import "CTPPhoneSelectorController.h"
#import "MBProgressHUD+PKX.h"
#import "CTPMsgViewModel.h"
#import "CTPMessage.h"
#import <sqlite3.h>
//#import "HMImagePickerController.h"
//#import "PhotoPickerCell.h"
#import "CTPPhotosCollectionView.h"
static NSInteger maxOfLength = 25;

@interface CTPComposeViewController ()<UITextViewDelegate>

@property(nonatomic,strong) CTPPhotosCollectionView *collectionView;
@property (nonatomic, strong) CTPPlaceholderTextView *textView;

// 自定义toolBar
@property (nonatomic, strong) UIToolbar *toolBar;

// 照片的view是否显示
@property (nonatomic, assign) BOOL isShowPhotoSelectorView;
// 图片选择控制器
@property (nonatomic, strong) CTPPhoneSelectorController *photoSelectorVC;

// 自定义的一个uilabel
@property (nonatomic, strong) UILabel *lengthTipLabel;



///**
// *  存储选择图片的数组
// */
//@property(nonatomic,strong) NSMutableArray<UIImage *> *images;
//@property(nonatomic,strong) NSMutableArray<PHAsset *> *selectedAssets;
///**
// *  展示图片的collectionView
// */
//@property(nonatomic, weak) IBOutlet UICollectionView *collectionView;
///**
// *  layout
// */
//@property(nonatomic,strong) IBOutlet UICollectionViewFlowLayout *layout;
///**
// *  相片选择器
// */
//@property(nonatomic,strong) HMImagePickerController *picker;
@end

@implementation CTPComposeViewController


-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (self.isShowPhotoSelectorView) {
        [self.textView becomeFirstResponder];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self textView];
    [self toolBar];
    [self prepareUI];
    // 监听键盘frame的改变
    //
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

// 监听键盘的改变
-(void)willChangeFrame:(NSNotification *)notification{
    CGRect frame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey]CGRectValue];
    CGFloat duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey]doubleValue];
    CGFloat y = frame.origin.y - [UIScreen mainScreen].bounds.size.height;
    //    // 动画
    [_toolBar mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(y);
    }];
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
    
}
// 移除通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}



#pragma mark  自定义toolbar中的问题点击响应事件
- (CTPPhotosCollectionView *)collectionView {
    if (_collectionView == nil) {
        _collectionView = [CTPPhotosCollectionView collectionView];
        _collectionView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height * 0.6);
        _collectionView.backgroundColor = [UIColor whiteColor];
        __weak typeof(self) weakVC = self;
        [_collectionView setJumpToVCBlock:^(UIViewController *vc) {
            [weakVC presentViewController:vc animated:YES completion:nil];
        }];
        [self.view addSubview:_collectionView];
    }
    return _collectionView;
}
-(void) picture{
//    self.isShowPhotoSelectorView = YES;
//    [self.photoSelectorVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.bottom.equalTo(self.view).offset(0);
//    }];
//    [UIView animateWithDuration:0.25 animations:^{
//        [self.view layoutIfNeeded];
//    }];
    //  让键盘退下
    [self.textView resignFirstResponder];
    
    // 动画弹出collectionView
    [UIView animateWithDuration:0.25 animations:^{
        self.collectionView.frame = CGRectMake(0, [UIScreen mainScreen].bounds.size.height * 0.4, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height * 0.6);
    }];
    
}

-(void)del{
//
//    self.isShowPhotoSelectorView = NO;
    //  让键盘退下
    [self.textView resignFirstResponder];
}


-(void) setupToolBar{
    // 每个item对应的图片名称
    [_toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    NSMutableArray *arrayM1 = @[@{@"imageName": @"compose_toolbar_picture",@"action": @"picture"},@{@"imageName": @"compose_emotion_delete",@"action": @"del"}];
    
    NSMutableArray *items = [NSMutableArray array];
    [arrayM1 enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *imageName =  obj[@"imageName"];
        NSString *action1 = obj[@"action"];
        
        UIBarButtonItem *item = [[UIBarButtonItem alloc]init:imageName target:self action:NSSelectorFromString(action1)];
        UIButton *btn = [item customView];
        btn.tag = idx;
        [items addObject:item];
        
        UIBarButtonItem *flexibleBtn = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
        [items addObject:flexibleBtn];
    }];
    [items removeLastObject];
    _toolBar.items = items;
}

-(void) setupNavigationBar{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(closed)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendMsgs)];
    [self setupTitleView];
}

/// 设置TitleView
-(void) setupTitleView{
        NSString *prefix = @"记录笔记";
        NSString *name = @"123";
        NSString *title = [NSString stringWithFormat:@"%@\n%@",prefix,name];
        UILabel *titleLabel = [[UILabel alloc]init];
        titleLabel.numberOfLines = 0;
        titleLabel.textAlignment =NSTextAlignmentCenter;
        titleLabel.textColor = [UIColor blackColor];
        titleLabel.font = [UIFont systemFontOfSize:14];
        //        属性文本
        NSMutableAttributedString *attStringM = [[NSMutableAttributedString alloc]initWithString:title];
        NSRange range = [title rangeOfString:name];
        [attStringM addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:range];
        [attStringM addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:range];
        titleLabel.attributedText = attStringM;
        [titleLabel sizeToFit];
        self.navigationItem.titleView = titleLabel;
        self.navigationItem.title = prefix;
}
// 取消
-(void)closed{
    // textView取消第一相应者,键盘就会退下
    [_textView resignFirstResponder];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

// 发送
-(void)sendMsgs{
    NSString *text = self.textView.text;
    // 判断是否超出了长度
    NSInteger last=maxOfLength-text.length;
    if (last<0) {
        [MBProgressHUD showError:@"超出最大长度"];
        return;
    }
    // 提示正在发微博
    [MBProgressHUD showMessage:@"正在发布..."];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 隐藏登录指示器
        [MBProgressHUD hideHUD];
        // 提示登录成功
        [MBProgressHUD showSuccess:@"发布成功"];
        // 去照片选择器里面拿图片
        UIImage *image= self.photoSelectorVC.photos.firstObject;
        NSMutableArray *imagearr = [[NSMutableArray alloc] init];
        
        if (image) {
            NSString *randomImageName = [NSString stringWithFormat:@"%zd",arc4random_uniform(100)];
            
            NSString *filePath =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"image/png"];
            NSString *imagePath =[filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",randomImageName,@".png"]];
            
            [imagearr addObject:image];

        }
        
        
//        利用sqlite数据库的blob类型的数据存取
        
//        假定数据库中存在表 imageTable(name text,image blob), 下面代码将图片文件test.png的二进制数据写到sqlite数据库
        
//                NSData *data=UIImagePNGRepresentation(image);
        
//        //把图片转换为Base64的字符串
//        NSString *image64 = [self encodeToBase64String:image];
//        [arr addObject:image64];
//        //写入plist文件
//        if ([arr writeToFile:newPath atomically:YES]) {
//            NSLog(@写入成功);
//        };
        
        //获得系统时间
        NSDate *  senddate=[NSDate date];
        NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
        [dateformatter setDateFormat:@"HH:mm:ss"];
        NSString *  locationString=[dateformatter stringFromDate:senddate];
        //获得系统日期
        NSCalendar  * cal=[NSCalendar  currentCalendar];
        NSUInteger  unitFlags=NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit;
        NSDateComponents * conponent= [cal components:unitFlags fromDate:senddate];
        NSInteger year=[conponent year];
        NSInteger month=[conponent month];
        NSInteger day=[conponent day];
#warning 存放到数据库中的日期格式定死为2014/08/12 00:00:00
//        NSString *nsDateString= [NSString  stringWithFormat:@"%4ld年%2ld月%2ld日%@",year,month,day,locationString];
        NSString *nsDateString= [NSString  stringWithFormat:@"%4ld/%2ld/%2ld %@",year,month,day,locationString];
        NSString *imageName = [NSString stringWithFormat:@"%@",nsDateString];
        
        
        
#warning  发送说说的回调方法
        CTPMessage *message =[[CTPMessage alloc]initWithTitleId:1 content:text created_at:imageName imgsArray:imagearr];
        [[CTPMsgViewModel sharedMsgInstance]insertMsgs:message];
//      返回到列表
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}

-(void) prepareUI{
    [self setupNavigationBar];
    [self setupTextView];
//  设置照片选择器的view
    [self setupPhotoSelectorView];
    [self setupToolBar];
    [self setupLengthTipLabel];
}
-(void) setupLengthTipLabel{
    [self.view addSubview:self.lengthTipLabel];
    [self.lengthTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.toolBar.mas_top).offset(-4);
        make.trailing.equalTo(self.toolBar).offset(-4);
    }];
}

//将照片选择控制器的view添加到发微博控制器的view里面
-(void) setupPhotoSelectorView{
//   设置照片选择控制器
    UIView *photoSelectorView =self.photoSelectorVC.view;
    [self.view addSubview:photoSelectorView];
    // 当一个控制器的view成为另一个控制器的view的子view,那么这个控制器页最好成为另外一个控制器的子控制器
    [self addChildViewController:self.photoSelectorVC];
    //  添加约束
    [photoSelectorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view).offset([UIScreen mainScreen].bounds.size.height * 0.6);
        make.height.mas_equalTo([UIScreen mainScreen].bounds.size.width * 0.6);
    }];
}

-(void) setupTextView{
    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

#pragma mark - 懒加载
- (CTPPhoneSelectorController *)photoSelectorVC{
    if (_photoSelectorVC==nil) {
        _photoSelectorVC = [[CTPPhoneSelectorController alloc]init];
    }
    return _photoSelectorVC;
}

- (UILabel *)lengthTipLabel{
    if (_lengthTipLabel==nil) {
        _lengthTipLabel = [[UILabel alloc]init];
        _lengthTipLabel.font = [UIFont systemFontOfSize:10];
        _lengthTipLabel.text= [NSString stringWithFormat:@"%ld",maxOfLength];
        [_lengthTipLabel sizeToFit];
    }
    return _lengthTipLabel;
}
- (CTPPlaceholderTextView *)textView{
    if (_textView == nil) {
        CTPPlaceholderTextView *tv = [[CTPPlaceholderTextView alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width*0.5, [UIScreen mainScreen].bounds.size.height*0.5)];
        tv.font = [UIFont systemFontOfSize:14];
        [tv setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg4.jpg"]]];
        tv.textColor = [UIColor grayColor];
        tv.text = @"写点什么吧......";
        self.textView = tv;
        [self.view addSubview:tv];
    
        //监听textView文字的改变
        tv.delegate = self;
        //垂直弹簧效果
        tv.alwaysBounceVertical = YES;
        //当拖拽textView就会关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _textView;
}

- (UIToolbar *)toolBar{
    if (_toolBar ==nil) {
        UIToolbar *toolBar = [[UIToolbar alloc]init];
        [self.view addSubview:toolBar];
        _toolBar = toolBar;
    }
    return _toolBar;
}

#pragma mark -textview 的代理方法
-(void) textViewDidChange:(UITextView *)textView{
    self.navigationItem.rightBarButtonItem.enabled =[textView hasText];
//  已经输入文本
    NSString *text = self.textView.text;
    // 计算剩余文本的长度
    NSInteger last = maxOfLength - text.length;
    self.lengthTipLabel.text = [NSString stringWithFormat:@"%ld",last];
    UIColor *color =  last<0 ? [UIColor redColor]:[UIColor lightGrayColor];
    self.lengthTipLabel.textColor = color;
}



//#pragma mark - 新增方法
//- (void)didClickAddBtn {
//    self.picker = [[HMImagePickerController alloc] initWithSelectedAssets:self.selectedAssets];
//    self.picker.pickerDelegate = self;
//    // 设置目标图片尺寸
//    self.picker.targetSize = CGSizeMake(600, 600);
//    // 设置最大选择照片的数量
//    self.picker.maxPickerCount = 9;
//    // 进入选择照片控制器
//    [self presentViewController:self.picker animated:YES completion:nil];
//}
//- (void)didClickDeleteBtn:(PhotoPickerCell *)cell {
//    // 移除对象
//    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
//    [self.images removeObjectAtIndex:indexPath.item];
//    [self.selectedAssets removeObjectAtIndex:indexPath.item];
//    // 刷新选择
//    [self.collectionView reloadData];
//}
//
//#pragma mark - 实现黑马选择器的代理
//- (void)imagePickerController:(HMImagePickerController *)picker didFinishSelectedImages:(NSArray<UIImage *> *)images selectedAssets:(NSArray<PHAsset *> *)selectedAssets {
//    // 获得的图片
//    [self.images addObjectsFromArray:images];
//    // 已经选择的图片
//    [self.selectedAssets addObjectsFromArray:selectedAssets];
//    // 退出照片选择器
//    [self.picker dismissViewControllerAnimated:YES completion:nil];
//    // 刷新显示
//    [self.collectionView reloadData];
//}
//#pragma mark - collectionView
//- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
//    // 返回比选择的照片多一个
//    CGFloat count = self.images.count != 0 ? self.images.count + 1 : 1;
//    if (self.images.count == 0) {
//        count = 1;
//    } else if (self.images.count < 9) {
//        count = self.images.count + 1;
//    } else {
//        count = 9;
//    }
//    return count;
//}
//- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
//    PhotoPickerCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"photos" forIndexPath:indexPath];
//    // 传递图片
//    if (indexPath.item < self.images.count) {
//        cell.image = self.images[indexPath.item];
//    } else {
//        [cell showAddBtn];
//    }
//    // 删除选择的图片
//    __weak typeof(cell) weakCell = cell;
//    [cell setDeleteImagesBlock:^{
//        [self didClickDeleteBtn:weakCell];
//    }];
//    // 选择图片
//    [cell setPickerImagesBlock:^{
//        [self didClickAddBtn];
//    }];
//    return cell;
//}
//- (void)setupCollection {
//    // 设置背景
//    self.collectionView.backgroundColor = [UIColor whiteColor];
//    // 指定数据源额代理
//    self.collectionView.dataSource = self;
//    self.collectionView.delegate = self;
//    // 设置layout
//    self.layout.itemSize = CGSizeMake(80, 80);
//    // 注册
//    [self.collectionView registerClass:[PhotoPickerCell class] forCellWithReuseIdentifier:@"photos"];
//    // 设置基本间距
//    self.collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10);
//}
@end
